import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
       
        int row = matrix.length;
        int col = matrix[0].length;
        ArrayList<Integer> res = new ArrayList<>();

        if (row == 0) 
            return res;
 
        int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int index = 0;
        int cnt = 0;
        int x = 0, y = 0;

        while (cnt < row * col) {
            res.add(matrix[x][y]);
            matrix[x][y] = Integer.MIN_VALUE;
            cnt++;

            int tempX = x + dir[index][0];
            int tempY = y + dir[index][1];
            if (tempX < row && tempX >= 0 && tempY >= 0 && tempY < col ) {
                if (matrix[tempX][tempY] != Integer.MIN_VALUE) {
                    x = tempX;
                    y = tempY;
                }
                else {
                    index = (index + 1) % 4;
                    x = x + dir[index][0];
                    y = y + dir[index][1];
                }
            }
            else {
                index = (index + 1) % 4;
                x = x + dir[index][0];
                y = y + dir[index][1];
            }
        }
        
        return res;
    }
}